package itsm.isperp.module.controller.individuation;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseProcessController;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.project.ProjectDomain;
import itsm.isperp.module.entity.app.AppMessageRemind;
import itsm.isperp.module.entity.individuation.IddIndividuation;
import itsm.isperp.module.service.app.AppMessageRemindService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.individuation.IddIndividuationService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.utils.ProjectDomainUtils;
import itsm.isperp.workflow.service.BpmProcessDefinitaionService;
import itsm.isperp.workflow.service.BpmProcessRunService;
import itsm.isperp.workflow.utils.BpmConst;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 控制器
 * 
 * @author lizx
 * @date 2016-10-10 17:41
 */
@Controller
@RequestMapping("individuation/individuation")
public class IddIndividuationController extends BaseProcessController<IddIndividuation> {

	@Autowired
	protected IddIndividuationService iddIndividuationService;

	@Autowired
	protected AppUserService appUserService;

	@Override
	public IddIndividuationService getService() {
		return this.iddIndividuationService;
	}

	@Override
	public String getPageTitle() {
		return "个性化流程";
	}

	@Override
	public String getProceessKey() {
		return "individuationProcess";
	}

	@RequestMapping("searchManage")
	public ModelAndView searchManage() {
		ModelAndView mv = new ModelAndView("individuation/individuation/searchManage");
		List<Map<String,Object>> list=this.getService().listIddIndividuationProcess();
		mv.addObject("processList", list);
		return mv;
	}

	@RequestMapping("listData")
	@ResponseBody
	public PageResponse<Map<String, Object>> listData(JqGridRequest request, HttpServletRequest req) {

		String projectId = req.getParameter("projectId");
		if (StringUtils.isNotEmpty(projectId)) {
			request.addFilterRule("projectId", JqGridFilterRuleOp.eq, projectId);
		}
		request.setSearchString("  1=1 " + ProjectDomainUtils.getUserDomainSql(ProjectDomain.newInstance()));
		String ifShowExtend = req.getParameter("ifShowExtend");
		if (StringUtils.isNotEmpty(ifShowExtend) && ifShowExtend.equals("1")) {
			String categoryId = req.getParameter("categoryId");
			return this.getService().findWithPropertyMapByRequest(categoryId, request);
		}
		PageResponse<Map<String, Object>> p = this.getService().findAllDetailByRequest(request).toPage();
		return p;
	}
	
	
	@RequestMapping("testPageEdit")
  public ModelAndView testPageEdit(String id, HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    
    return mv;
  }

	@RequestMapping("edit")
	@Override
	public ModelAndView edit(String id, HttpServletRequest req) throws Exception {
		ModelAndView mv = this.getModelAndView();
		IddIndividuation model = null;
		String processKey = req.getParameter("processKey");
		String processName = "";
		String categoryId = "";
		if (StringUtils.isEmpty(id)) {
			model = new IddIndividuation();
			model.setId(HibernateUUIDGenerator.generate());
			processName = this.getService().getProcessNameByProcessKey(processKey);
			categoryId=this.getService().getCategoryIdByProcessKey(processKey);
		} else {
			model = this.getService().findOne(id);
			processKey = model.getProcessKey();
			processName = model.getProcessName();
			categoryId = model.getCategoryId();
		}
		if (StringUtils.isBlank(processKey)) {
			processKey = "individuationProcess";
		}
		
		String processId=model.getProcessId();
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    BpmProcessDefinitaionService bpmProcessDefinitaionService = ContextHolder
        .getSpringBean("bpmProcessDefinitaionService");

    if (StringUtils.isNotEmpty(processId)) {
      Map<String, Object> map = bpmProcessRunService.trace(processId);
      String areRunning = (String) map.get("areRunning");
      if(areRunning.equals("1"))
      {
        String nodeId=map.get("currentTaskTaskDefinitionKey").toString();
        mv.addObject("nodeId", nodeId);
      }
        
    }else
    {
      
      String nodeId=bpmProcessDefinitaionService.getProcessDefinitionEntityByKey(processKey).getInitial().getId();
      mv.addObject("nodeId", nodeId);
    }
		
		ProjProjectService projProjectService = ContextHolder.getSpringBean("projProjectService");

		String carbonCategoryId = req.getParameter("categoryId");
		if (StringUtils.isEmpty(carbonCategoryId))
			carbonCategoryId = categoryId;
		mv.addObject("categoryId", categoryId);
		mv.addObject("carbonCategoryId", carbonCategoryId);
		mv.addObject("processKey", processKey);
		model.setProcessKey(processKey);
		model.setProcessName(processName);
		model.setCategoryId(categoryId);
		mv.addObject("model", model);
		mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
	  AppMessageRemindService appMessageRemindService = ContextHolder.getSpringBean("appMessageRemindService");
    JqGridRequest req1 = new JqGridRequest();
    req1.isPageable(false);
    req1.setSort("create_date", Direction.DESC);
    req1.addFilterRule("source_id", JqGridFilterRuleOp.eq, model.getId());
    List<AppMessageRemind> lr = appMessageRemindService.findAll(req1)
        .getContent();
    mv.addObject("arMsgList", lr);
		return mv;
	}
	
	@RequestMapping("blackEdit")
  public ModelAndView blackEdit(String id, HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    IddIndividuation model = null;
    String processKey = req.getParameter("processKey");
    String processName = "";
    String categoryId = "";
    if (StringUtils.isEmpty(id)) {
      model = new IddIndividuation();
      model.setId(HibernateUUIDGenerator.generate());
      processName = this.getService().getProcessNameByProcessKey(processKey);
      categoryId=this.getService().getCategoryIdByProcessKey(processKey);
    } else {
      model = this.getService().findOne(id);
      processKey = model.getProcessKey();
      processName = model.getProcessName();
      categoryId = model.getCategoryId();
    }
    if (StringUtils.isBlank(processKey)) {
      processKey = "individuationProcess";
    }
    ProjProjectService projProjectService = ContextHolder.getSpringBean("projProjectService");

    String carbonCategoryId = req.getParameter("categoryId");
    if (StringUtils.isEmpty(carbonCategoryId))
      carbonCategoryId = categoryId;
    mv.addObject("categoryId", categoryId);
    mv.addObject("carbonCategoryId", carbonCategoryId);
    mv.addObject("processKey", processKey);
    model.setProcessKey(processKey);
    model.setProcessName(processName);
    model.setCategoryId(categoryId);
    mv.addObject("model", model);
    mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
    AppMessageRemindService appMessageRemindService = ContextHolder.getSpringBean("appMessageRemindService");
    JqGridRequest req1 = new JqGridRequest();
    req1.isPageable(false);
    req1.setSort("create_date", Direction.DESC);
    req1.addFilterRule("source_id", JqGridFilterRuleOp.eq, model.getId());
    List<AppMessageRemind> lr = appMessageRemindService.findAll(req1)
        .getContent();
    mv.addObject("arMsgList", lr);
    return mv;
  }
	

	@RequestMapping(value = { "view"})
	@Override
	public ModelAndView view(String id, HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		IddIndividuation model = null;
		String processName = "";
		String categoryId = "";
		String processKey = req.getParameter("processKey");
		model = this.getService().findOne(id);
		if (StringUtils.isBlank(processKey)) {
			processKey = model.getProcessKey();
			processName = model.getProcessName();
			categoryId = model.getCategoryId();
		}
		Map<String, Object> cusUser = this.appUserService.findOneDetailById(model.getCusUserId());
		mv.addObject("cusUser", cusUser);

		if (StringUtils.isBlank(processKey)) {
			processKey = "individuationProcess";
		}
		ProjProjectService projProjectService = ContextHolder.getSpringBean("projProjectService");
		if (StringUtils.isBlank(categoryId)) {
			categoryId = this.getService().getCategoryIdByProcessKey(processKey);
		}
		String carbonCategoryId = req.getParameter("categoryId");
		if (StringUtils.isEmpty(carbonCategoryId))
			carbonCategoryId = categoryId;
		mv.addObject("categoryId", categoryId);
		mv.addObject("carbonCategoryId", carbonCategoryId);
		mv.addObject("processKey", processKey);
		model.setProcessName(processName);
		mv.addObject("model", model);
		mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
		mv.addObject("readOnly", "true");
		return mv;
	}
	
	@RequestMapping(value = { "blackView"})
  public ModelAndView blackView(String id, HttpServletRequest req) {
    ModelAndView mv = this.getModelAndView();
    IddIndividuation model = null;
    String processName = "";
    String categoryId = "";
    String processKey = req.getParameter("processKey");
    model = this.getService().findOne(id);
    if (StringUtils.isBlank(processKey)) {
      processKey = model.getProcessKey();
      processName = model.getProcessName();
      categoryId = model.getCategoryId();
    }
    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model.getCusUserId());
    mv.addObject("cusUser", cusUser);

    if (StringUtils.isBlank(processKey)) {
      processKey = "individuationProcess";
    }
    ProjProjectService projProjectService = ContextHolder.getSpringBean("projProjectService");
    if (StringUtils.isBlank(categoryId)) {
      categoryId = this.getService().getCategoryIdByProcessKey(processKey);
    }
    String carbonCategoryId = req.getParameter("categoryId");
    if (StringUtils.isEmpty(carbonCategoryId))
      carbonCategoryId = categoryId;
    mv.addObject("categoryId", categoryId);
    mv.addObject("carbonCategoryId", carbonCategoryId);
    mv.addObject("processKey", processKey);
    model.setProcessName(processName);
    mv.addObject("model", model);
    mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
    mv.addObject("readOnly", "true");
    return mv;
  }

	@RequestMapping("handleEdit")
	public ModelAndView handleEdit(String id, HttpServletRequest req) {

		ModelAndView mv = this.getModelAndView();
		IddIndividuation model = null;
		String processName = "";
		String categoryId = "";
		String processKey = req.getParameter("processKey");
		if (StringUtils.isEmpty(id)) {
			model = new IddIndividuation();
			model.setId(HibernateUUIDGenerator.generate());
		} else {
			model = this.getService().findOne(id);
			if (StringUtils.isBlank(processKey)) {
				processKey = model.getProcessKey();
				processName = model.getProcessName();
				categoryId = model.getCategoryId();
			}
			Map<String, Object> cusUser = this.appUserService.findOneDetailById(model.getCusUserId());

			mv.addObject("cusUser", cusUser);
		}
		if (StringUtils.isBlank(processKey)) {
			processKey = "individuationProcess";
		}
		ProjProjectService projProjectService = ContextHolder.getSpringBean("projProjectService");
		if (StringUtils.isBlank(categoryId)) {
			categoryId = this.getService().getCategoryIdByProcessKey(processKey);
		}
		String carbonCategoryId = req.getParameter("categoryId");
		if (StringUtils.isEmpty(carbonCategoryId))
			carbonCategoryId = categoryId;
		mv.addObject("categoryId", categoryId);
		mv.addObject("carbonCategoryId", carbonCategoryId);
		mv.addObject("processKey", processKey);
		model.setProcessName(processName);
		mv.addObject("model", model);
		mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
		
		String processId=model.getProcessId();
		BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");

    if (StringUtils.isNotEmpty(processId)) {
      Map<String, Object> map = bpmProcessRunService.trace(processId);
      String areRunning = (String) map.get("areRunning");
      if(areRunning.equals("1"))
      {
        String nodeId=map.get("currentTaskTaskDefinitionKey").toString();
        mv.addObject("nodeId", nodeId);
      }
        
    }

    
		
		return mv;
	}
	
	@RequestMapping("blackHandlerEdit")
  public ModelAndView blackHandlerEdit(String id, HttpServletRequest req) {

    ModelAndView mv = this.getModelAndView();
    IddIndividuation model = null;
    String processName = "";
    String categoryId = "";
    String processKey = req.getParameter("processKey");
    if (StringUtils.isEmpty(id)) {
      model = new IddIndividuation();
      model.setId(HibernateUUIDGenerator.generate());
    } else {
      model = this.getService().findOne(id);
      if (StringUtils.isBlank(processKey)) {
        processKey = model.getProcessKey();
        processName = model.getProcessName();
        categoryId = model.getCategoryId();
      }
      Map<String, Object> cusUser = this.appUserService.findOneDetailById(model.getCusUserId());

      mv.addObject("cusUser", cusUser);
    }
    if (StringUtils.isBlank(processKey)) {
      processKey = "individuationProcess";
    }
    ProjProjectService projProjectService = ContextHolder.getSpringBean("projProjectService");
    if (StringUtils.isBlank(categoryId)) {
      categoryId = this.getService().getCategoryIdByProcessKey(processKey);
    }
    String carbonCategoryId = req.getParameter("categoryId");
    if (StringUtils.isEmpty(carbonCategoryId))
      carbonCategoryId = categoryId;
    mv.addObject("categoryId", categoryId);
    mv.addObject("carbonCategoryId", carbonCategoryId);
    mv.addObject("processKey", processKey);
    model.setProcessName(processName);
    mv.addObject("model", model);
    mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
    
    String processId=model.getProcessId();
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");

    if (StringUtils.isNotEmpty(processId)) {
      Map<String, Object> map = bpmProcessRunService.trace(processId);
      String areRunning = (String) map.get("areRunning");
      if(areRunning.equals("1"))
      {
        String nodeId=map.get("currentTaskTaskDefinitionKey").toString();
        mv.addObject("nodeId", nodeId);
      }
        
    }

    
    
    return mv;
  }
	
	@RequestMapping("handle2Edit")
	public ModelAndView handle2Edit(String id, HttpServletRequest req) {

		ModelAndView mv = this.getModelAndView();
		IddIndividuation model = null;
		String processName = "";
		String categoryId = "";
		String processKey = req.getParameter("processKey");
		if (StringUtils.isEmpty(id)) {
			model = new IddIndividuation();
			model.setId(HibernateUUIDGenerator.generate());
		} else {
			model = this.getService().findOne(id);
			if (StringUtils.isBlank(processKey)) {
				processKey = model.getProcessKey();
				processName = model.getProcessName();
				categoryId = model.getCategoryId();
			}
			Map<String, Object> cusUser = this.appUserService.findOneDetailById(model.getCusUserId());

			mv.addObject("cusUser", cusUser);
		}
		if (StringUtils.isBlank(processKey)) {
			processKey = "individuationProcess";
		}
		ProjProjectService projProjectService = ContextHolder.getSpringBean("projProjectService");
		if (StringUtils.isBlank(categoryId)) {
			categoryId = this.getService().getCategoryIdByProcessKey(processKey);
		}
		String carbonCategoryId = req.getParameter("categoryId");
		if (StringUtils.isEmpty(carbonCategoryId))
			carbonCategoryId = categoryId;
		mv.addObject("categoryId", categoryId);
		mv.addObject("carbonCategoryId", carbonCategoryId);
		mv.addObject("processKey", processKey);
		model.setProcessName(processName);
		mv.addObject("model", model);
		mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
	  String processId=model.getProcessId();
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");

    if (StringUtils.isNotEmpty(processId)) {
      Map<String, Object> map = bpmProcessRunService.trace(processId);
      String areRunning = (String) map.get("areRunning");
      if(areRunning.equals("1"))
      {
        String nodeId=map.get("currentTaskTaskDefinitionKey").toString();
        mv.addObject("nodeId", nodeId);
      }
        
    }
		return mv;
	}

	@RequestMapping("form3Edit")
	public ModelAndView form3Edit(String id, HttpServletRequest req) {

		ModelAndView mv = new ModelAndView();
		IddIndividuation model = this.getService().findOne(id);
		mv.addObject("model", model);
		return mv;
	}

	@RequestMapping("listDetail")
	@ResponseBody
	@Override
	public PageResponse<Map<String, Object>> listDetail(JqGridRequest request, HttpServletRequest req) {
		return this.getListDetail(iddCountQuery(), request, req);
	}

	@Override
	@RequestMapping("approvalCount")
	@ResponseBody
	public Long approvalCount() {
		return this.createMyFlowCountQuery().getTreeNodeCount(TODO_TASK);
	}
	
	@RequestMapping("requestSaveOrUpdate")
  @ResponseBody
  public ResultMessage requestSaveOrUpdate(HttpServletRequest req) {
	  Map<String, String[]> pa = req.getParameterMap();
	  Set<String> set = pa.keySet();
	  String columns="";
	  String description="";
	  //获取字段属性名
	  for (String k : set) {
      if (k.indexOf("c_") > -1) {
        columns+="'"+k.substring(2,k.length())+"',";
      }
	  }
	  JdbcTemplate jdbcTemplate=ContextHolder.getSpringBean("jdbcTemplate");
	  IcdIncidentService icdIncidentService=ContextHolder.getSpringBean("icdIncidentService");
	  columns=columns.substring(0,columns.length()-1);
	  if(StringUtils.isNotBlank(columns))
	  {
	    String sql="SELECT * FROM idd_category_property where id in("+columns+") order by order_num";
	    List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
	    for(Map<String,Object> li:list)
	    {
	      String zhName=li.get("name").toString();
	      String id=li.get("id").toString();
	      String kv = "";
        String[] proValue = pa.get("c_"+id);
        for (String s1 : proValue) {
          kv += s1 + ",";
        }
        if(StringUtils.isNoneBlank(kv))
        {
          kv = kv.substring(0, kv.length() - 1);
          description+=zhName+"： "+kv+"\n";
        }

	    }
	    
	  }
	  boolean result=icdIncidentService.submitNewIncident("", description, "");
    return ResultMessage.newInstance(result, "", "");
  }

	protected CountQuery createMyFlowCountQuery() {
		CountQuery cq = createDefaultCountQuery();
		cq.addCountFilter(TODO_TASK, true, BpmConst.getQueryMyTaskSqlCondition(""));
		return cq;
	}

	protected CountQuery iddCountQuery() {
		CountQuery cq = createDefaultCountQuery();
		cq.addCountFilter(TODO_TASK, true, BpmConst.getQueryMyTaskSqlCondition(""));
		cq.addCountFilter(HAVETODO_TASK, BpmConst.getQueryMyTaskAttendSqlCondition(""));
		cq.addCountFilter(START_TASK, BpmConst.getQueryMyTaskStartedSqlCondition(""));
		cq.addCountFilter(DRAFT_TASK, new StringBuffer(" ( process_id IS NULL AND  creator ='").append(ContextHolder.getLoginUsername()).append("') ").toString());
		return cq;
	}

}
